#include "MySQLclient.hpp"
#include <cstdio>
#include <cstdlib>
#include <mysql/client_plugin.h>
#include <mysql/mysql.h>

namespace wd
{
MySQLClient::~MySQLClient(){
    if(_res){
        mysql_free_result(_res);
    }

    if(_conn){
        mysql_close(_conn);
    }
}

void MySQLClient::init(){
   _conn = mysql_init(_conn);
}

void MySQLClient::connect(const string& host,
                          const string& user,
                          const string& passwd,
                          const string& db,
                          unsigned short port)
{
    MYSQL *pcon = ::mysql_real_connect(_conn,
                                       host.c_str(),
                                       user.c_str(),
                                       passwd.c_str(),
                                       db.c_str(),
                                       port,
                                       nullptr,
                                       0);        
    if(!pcon){
        fprintf(stderr,"%s\n",mysql_error(_conn));
        exit(EXIT_FAILURE);
    }
    _conn = pcon;
}

bool MySQLClient::writeOperattionQuery(const string &sql){
    int ret = mysql_real_query(_conn,sql.c_str(),sql.size());
    if(ret !=0){
        fprintf(stderr,"ERROR %d : %s\n",
                mysql_errno(_conn),
                mysql_error(_conn));
        return false;
    }
    printf("QUERY OK,%ld row affectd\n",mysql_affected_rows(_conn));
    return true;
}

vector<vector<string>> MySQLClient::readOperationQuery(const string &sql){
    vector<vector<string>> str;
    
    bool flag = writeOperattionQuery(sql);
    if(!flag){
        exit(EXIT_FAILURE);
    }

    _res = mysql_store_result(_conn);
    if(!_res){
        fprintf(stderr,"error MYSQL_RES\n");
        exit(EXIT_FAILURE);
    }

    int cols = mysql_num_fields(_res);
    int cows = mysql_num_rows(_res);
    str.reserve(cows);
    str.emplace_back();

    MYSQL_FIELD *parr = mysql_fetch_fields(_res);
    for (int i=0;i<cols;i++){
        str[0].push_back(parr[i].name);
    }

    MYSQL_ROW row;
    while ((row = mysql_fetch_row(_res))!=nullptr){
        vector<string> head;
        head.reserve(cols);
        for(int i=0;i<cols;i++){
            head.emplace_back(row[i]);
        }
        str.push_back(head);
    }
    return str;
}


}//end of namespace

